#!/bin/bash

set -ex

export SETUP_LOG=/var/log/setup.log

touch $SETUP_LOG

# Start postgresql

cat >> /var/lib/postgresql/$POSTGRES_VERSION/main/pg_hba.conf <<-EOF
host   all       all       all           trust
EOF

cat >> /var/lib/postgresql/$POSTGRES_VERSION/main/postgresql.conf <<-EOF
logging_collector = on
log_min_messages = info
log_statement = 'all'
log_directory = '/var/log/postgresql/'
log_filename = 'postgresql-13-main.log'
listen_addresses = '*'
port = 6432
max_prepared_transactions = 5
shared_preload_libraries = 'pg_stat_statements,pg_stat_kcache,pg_comment_stats'
EOF

sudo -u postgres /usr/lib/postgresql/$POSTGRES_VERSION/bin/pg_ctl -D /var/lib/postgresql/$POSTGRES_VERSION/main/ start

if [[ -z "$POSTGRES_USER" ]]; then
    echo "ERROR: env.POSTGRES_USER is empty"
    exit 1
fi

if [[ -z "$POSTGRES_DB" ]]; then
    echo "ERROR: env.POSTGRES_DB is empty"
    exit 1
fi

# Create users
sudo -u postgres psql -p 6432 -h localhost -U postgres -c "CREATE ROLE $POSTGRES_USER WITH LOGIN SUPERUSER" -d postgres >> $SETUP_LOG 2>&1 || {
    echo "ERROR: users creation failed, examine the log"
    cat "$SETUP_LOG"
    exit 1
}

# Create databases
sudo -u postgres psql -p 6432 -h localhost -U postgres -c "CREATE DATABASE $POSTGRES_DB" -d postgres >> $SETUP_LOG 2>&1 || {
    echo "ERROR: databases creation failed, examine the log"
    cat "$SETUP_LOG"
    exit 1
}


# # Create extension
 sudo -u postgres psql -p 6432 -h localhost -U postgres -c "CREATE EXTENSION IF NOT EXISTS postgres_fdw; CREATE EXTENSION IF NOT EXISTS pg_stat_statements; CREATE EXTENSION IF NOT EXISTS pg_stat_kcache; CREATE EXTENSION IF NOT EXISTS pg_comment_stats;" -d $POSTGRES_DB >> $SETUP_LOG 2>&1 || {
     echo "ERROR: extensions creation failed, examine the log"
     cat "$SETUP_LOG"
     exit 1
 }

# # Grant permissions
# sudo -u postgres psql -p 6432 -h localhost -U postgres -c "ALTER ROLE $POSTGRES_USER SUPERUSER" -d db1 >> $SETUP_LOG 2>&1 || {
#     echo "ERROR: users creation failed, examine the log"
#     cat "$SETUP_LOG"
#     exit 1
# }

sudo -u postgres /usr/lib/postgresql/$POSTGRES_VERSION/bin/pg_ctl -D /var/lib/postgresql/$POSTGRES_VERSION/main/ stop
